package com.warski.wonderfires.utils.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuhaiping on 2020/9/2.
 */
public class NetworkChangeReceiver extends BroadcastReceiver {
    private List<NetworkChangedListener> listenerList = new ArrayList<>();

    public void registerReceiver(Context context) {
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(this, intentFilter);
    }

    public void unregisterReceiver(Context context) {
        context.unregisterReceiver(this);
    }

    public void addListener(NetworkChangedListener listener) {
        listenerList.add(listener);
    }

    public void removeListener(NetworkChangedListener listener) {
        listenerList.remove(listener);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            EnumNetworkType networkType = NetworkUtils.getNetworkType(context);
            for(NetworkChangedListener listener : listenerList){
                listener.onNetworkChanged(networkType);
            }
        }
    }
}
